package com.zretc.testcontroller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class AjaxRequestTest
 */
@WebServlet("/AjaxRequestTest")
public class AjaxRequestTest extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AjaxRequestTest() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置响应的编码
		response.setContentType("application/json;charset=utf-8");

		List<NewsType> list = new ArrayList<NewsType>();
		// 1创建一个PrintWriter对象
		PrintWriter out = response.getWriter();
		// 2 打印，将数据返回给页面
		NewsType newsType1 = new NewsType(1, "测试类型1");
		NewsType newsType2 = new NewsType(2, "测试类型2");
		// 实际操作的时候，数据应该是从service ->dao->数据库返回的。
		list.add(newsType1);
		list.add(newsType2);
		// 3将newsType对象存储到集合中

		Gson gson = new Gson();
		String jsonString = gson.toJson(list);
		// 记得打印的数据是返回的json字符串
		out.print(jsonString);
		// 3记得要关闭printWriter
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
